package com.tms.pidan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.pinda.authority.entity.common.Area;
import com.itheima.pinda.base.R;
import com.tms.pidan.service.AreaService;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/area")
public class AreaController {
    @Autowired
    AreaService areaService;

    @GetMapping("/findById/{id}")
    public Area getArea(@PathVariable(value = "id")Long id){
        return areaService.getById(id);
    }

    @PostMapping("/addArea")
    public Boolean addArea(@RequestBody Area area){
        Boolean flag = false;
        if(area != null){
            flag = areaService.save(area);
        }
        return flag;
    }

    @DeleteMapping("/deleteById/{id}")
    public Boolean deleteArea(@PathVariable(value = "id") String id){
        Boolean flag = false;
        if(!StringUtil.isNullOrEmpty(id)){
            flag = areaService.removeById(id);
        }
        return flag;
    }

    @GetMapping({"/code/{code}"})
    R<Area> getByCode(@PathVariable String code){
        LambdaQueryWrapper<Area> lambdaQueryWrapper = new LambdaQueryWrapper<Area>();
        lambdaQueryWrapper.eq(Area::getAreaCode,code);
        R<Area> result = null;
        Area area = areaService.getOne(lambdaQueryWrapper);
        if(area!=null){
            result = new R<Area>(500,null,"查询失败");
        }
        result= new R<Area>(200,area,"查询成功");
        return result;
    }

    @GetMapping
    R<List<Area>> findAll(@RequestParam(value = "parentId",required = false) Long parentId, @RequestParam(value = "ids",required = false) List<Long> ids){
        LambdaQueryWrapper<Area> lambdaQueryWrapper = new LambdaQueryWrapper<Area>();
        if(parentId!=null){
            lambdaQueryWrapper.eq(Area::getParentId,parentId);
        }
        if(ids != null && !ids.isEmpty()){
            lambdaQueryWrapper.in(Area::getId,ids);
        }
        R<List<Area>> result = null;
        List<Area> areasList = areaService.list(lambdaQueryWrapper);
        if(areasList.isEmpty()){
            result = new R<List<Area>>(500,null,"查询失败");
        }
        result= new R<List<Area>>(200,areasList,"查询成功");
        return result;
    }

    @PutMapping("/updateArea")
    public Boolean updateArea(@RequestBody Area area){
        Boolean flag = false;
        if(area != null){
            flag = areaService.updateById(area);
        }
        return flag;
    }
}
